﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SceneLib
{
    public class MathUtils
    {
        public static float[] GetVector3Array(Vector v)
        {
            float[] array = new float[3];
            array[0] = v.x;
            array[1] = v.y;
            array[2] = v.z;
            return array;
        }

        public static float[] GetVector4Array(Vector v)
        {
            float[] array = new float[4];
            array[0] = v.x;
            array[1] = v.y;
            array[2] = v.z;
            array[3] = 1;
            return array;
        }

        public static float[] GetMatrixArray(Matrix m)
        {
            float[] array = new float[16];
            int c = 0;

            for (int i = 0; i < 4; i++)
                for (int j = 0; j < 4; j++)
                {
                    array[c] = m.M[j, i];
                    ++c;
                }
            return array;
        }

        public static Vector Barycentric3D(Vector p, Vector a, Vector b, Vector c)
        {
            Vector n = Vector.Cross3(b - a, c - a);
            Vector na = Vector.Cross3(c - b, p - b);
            Vector nb = Vector.Cross3(a - c, p - c);
            Vector nc = Vector.Cross3(b - a, p - a);
            float alpha = Vector.Dot3(n, na) / Vector.Dot3(n, n);
            float beta = Vector.Dot3(n, nb) / Vector.Dot3(n, n);
            float gamma = Vector.Dot3(n, nc) / Vector.Dot3(n, n);
            Vector bar = new Vector(alpha, beta, gamma);
            return bar;
        }

        public static Vector Barycentric2D(float x, float y, float x0, float x1, float x2, float y0, float y1, float y2)
        {
            float alpha = ((y1 - y2) * x + (x2 - x1) * y + x1 * y2 - x2 * y1) / ((y1 - y2) * x0 + (x2 - x1) * y0 + x1 * y2 - x2 * y1);
            float beta = ((y2 - y0) * x + (x0 - x2) * y + x2 * y0 - x0 * y2) / ((y2 - y0) * x1 + (x0 - x2) * y1 + x2 * y0 - x0 * y2);
            float gamma = ((y0 - y1) * x + (x1 - x0) * y + x0 * y1 - x1 * y0) / ((y0 - y1) * x2 + (x1 - x0) * y2 + x0 * y1 - x1 * y0);

            return new Vector(alpha, beta, gamma);
        }

        public static float MinNum(float a, float b, float c)
        {
            float min = a;
            if (b < min)
                min = b;
            if (c < min)
                min = c;

            return min;
        }

        public static float MaxNum(float a, float b, float c)
        {
            float max = a;
            if (b > max)
                max = b;
            if (c > max)
                max = c;

            return max;
        }

       
    }
}
